import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ClipboardDemo(),
    );
  }
}

class ClipboardDemo extends StatefulWidget {
  const ClipboardDemo({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _ClipboardDemoState createState() => _ClipboardDemoState();
}

class _ClipboardDemoState extends State<ClipboardDemo> {
  String _clipboardContent = '当前剪贴板为空';
  final TextEditingController _clipboardController = TextEditingController();

  Future<void> _copyToClipboard(String text) async {
    await Clipboard.setData(ClipboardData(text: text));
  }

  Future<void> _getDataFromClipboard() async {
    ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
    setState(() {
      _clipboardContent = data?.text as String;
      // ignore: avoid_print
      print('剪贴板的复制内容：$_clipboardContent');
    });
  }

  @override
  void initState() {
    super.initState();
    //监听输入改变
    _clipboardController.addListener(() {
      // ignore: avoid_print
      print(_clipboardController.text);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Clipboard Demo"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(_clipboardContent),
          TextField(
            autofocus: true,
            controller: _clipboardController,
            decoration: const InputDecoration(
                labelText: "复制框",
                hintText: "请输入要复制的内容",
                prefixIcon: Icon(Icons.token)),
          ),
          ElevatedButton(
              child: const Text('复制上述内容到剪贴板'),
              onPressed: () {
                _copyToClipboard(_clipboardController.text);
              }),
          ElevatedButton(
              child: const Text('获取被复制内容'),
              onPressed: () {
                _getDataFromClipboard();
              }),
        ],
      ),
    );
  }
}
